package com.bm.specialvehiclefordispatcher.activity.setting;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.bm.corelibs.logic.BaseLogic.NListener;
import com.bm.corelibs.utils.ToastMgr;
import com.bm.specialvehiclefordispatcher.R;
import com.bm.specialvehiclefordispatcher.activity.BaseActivity;
import com.bm.specialvehiclefordispatcher.bean.BaseData;
import com.bm.specialvehiclefordispatcher.bean.Dispatcher;
import com.bm.specialvehiclefordispatcher.bean.TCity;
import com.bm.specialvehiclefordispatcher.constants.Constant;
import com.bm.specialvehiclefordispatcher.logics.LoginManager;
import com.bm.specialvehiclefordispatcher.logics.SettingManager;
import com.bm.specialvehiclefordispatcher.utils.CityCreator;
import com.bm.specialvehiclefordispatcher.utils.CityCreator.OnCityLoadedListener;
import com.bm.specialvehiclefordispatcher.utils.ImageUploader.OnResultListener;
import com.bm.specialvehiclefordispatcher.utils.CountDownTimer;
import com.bm.specialvehiclefordispatcher.utils.ImageUploader;
import com.bm.specialvehiclefordispatcher.views.CityPickerDialog;
import com.bm.specialvehiclefordispatcher.views.CityPickerDialog.onAddressSelectedListener;
import com.bm.specialvehiclefordispatcher.views.CommonNavigationBar;
import com.bm.specialvehiclefordispatcher.views.CustomDialog;
import com.makeramen.roundedimageview.RoundedTransformationBuilder;
import com.squareup.picasso.Picasso;

public class PersonInfoActivity extends BaseActivity implements OnClickListener, onAddressSelectedListener, OnCityLoadedListener, OnResultListener {

	CommonNavigationBar bar;
	ImageView personinfo_head;
	Button personinfo_uploadhead;
	RelativeLayout personinfo_name;
	RelativeLayout personinfo_tel;
	RelativeLayout personinfo_address;
	ImageUploader imageLoader;
	File imageFile;
	CustomDialog dialog;
	TextView ps_name;
	TextView ps_tel;
	TextView ps_address;
	private CityPickerDialog cityPicker;
	Dialog pitcureDialog;
	File photoFile;
	/**
	 * 倒计时
	 */
	private DownTimer timer;
	private Dispatcher dispatcher;
	private SettingManager manager = new SettingManager();
	private LoginManager loginManager = new LoginManager();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.actitity_personinfo);
		findViews();
		init();
		addListeners();
	}

	@Override
	public void findViews() {
		bar = (CommonNavigationBar) findViewById(R.id.navi);
		personinfo_head = (ImageView) findViewById(R.id.personinfo_head);
		personinfo_uploadhead = (Button) findViewById(R.id.personinfo_uploadhead);
		personinfo_name = (RelativeLayout) findViewById(R.id.personinfo_name);
		personinfo_tel = (RelativeLayout) findViewById(R.id.personinfo_tel);
		personinfo_address = (RelativeLayout) findViewById(R.id.personinfo_address);
		ps_name = (TextView) findViewById(R.id.ps_name);
		ps_tel = (TextView) findViewById(R.id.ps_tel);
		ps_address = (TextView) findViewById(R.id.ps_address);
	}

	@Override
	public void init() {
		dispatcher = LoginManager.getInstance(mActivity).getSavedUser();
		timer = new DownTimer(60 * 1000, 1000);
		imageLoader = new ImageUploader(mActivity);
		bar.setListener(null);
		bar.setTitle("个人资料");
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		if (dispatcher.name != null && !dispatcher.name.equals("null")) {
			ps_name.setText(dispatcher.name);
		}
		
		if (dispatcher.phone != null && !dispatcher.phone.equals("null")) {
			ps_tel.setText(dispatcher.phone);
		}
		
		if (dispatcher.address != null && !dispatcher.address.equals("null")) {
			ps_address.setText(dispatcher.address);
		}
		
		if (dispatcher.icon != null && !dispatcher.icon.equals("null"))	
			Picasso.with(mActivity).load(dispatcher.icon).resize(480, 480).centerCrop().transform(new RoundedTransformationBuilder().oval(true).build()).into(personinfo_head);
	}

	@Override
	public void addListeners() {
		personinfo_uploadhead.setOnClickListener(this);
		personinfo_name.setOnClickListener(this);
		personinfo_tel.setOnClickListener(this);
		personinfo_address.setOnClickListener(this);
		imageLoader.setOnResultListener(this);
	}

	@Override
	public void onClick(View v) {

		Intent intent;
		switch (v.getId()) {
		case R.id.personinfo_uploadhead:
			DisplayPhoto();
			break;
		case R.id.btn_takephoto1:
			String state = Environment.getExternalStorageState();
			if (state.equals(Environment.MEDIA_MOUNTED)) {
				intent = new Intent("android.media.action.IMAGE_CAPTURE");
				String fileName = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
				File pathdir = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera");
				if (!pathdir.exists()) {
					pathdir.mkdirs();
				}
				photoFile = new File(pathdir, fileName);
				// 指定调用相机拍照后的照片存储的路径
				intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
				startActivityForResult(intent, 1);
			} else {
				Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
			}

			pitcureDialog.dismiss();
			break;
		case R.id.btn_takephoto2:
			Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(galleryIntent, 2);
			pitcureDialog.dismiss();
			break;
		case R.id.btn_takephoto_cancel:
			pitcureDialog.dismiss();
			break;
		case R.id.personinfo_name:
			dialog = new CustomDialog(mActivity);
			dialog.show();
			dialog.setInputType(1);
			dialog.showTickAndEdit("修改姓名", "请输入个人姓名", new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (dialog.getTelText() != null && dialog.getTelText().length() > 0) {
						dispatcher.name = dialog.getTelText();
						dialog.dismiss();
						loadingDialog.show();
						manager.alterName(LoginManager.getInstance(mActivity).getId(), dispatcher.name, alterNameListener());
					} else {
						ToastMgr.show("请输入姓名");
					}
				}
			});
			break;
		case R.id.personinfo_tel:
			dialog = new CustomDialog(mActivity);
			dialog.show();
			dialog.setInputType(0);
			dialog.showSetTel("输入新手机号", "请输入旧手机号", "请输入您的手机号码", "验证码", new OnClickListener() {

				@Override
				public void onClick(View v) {

					// 获取验证码
					if (dialog.getTelText().length() == 11) {
						loginManager.getVCode(dialog.getTelText(), getVCodeListener());
						dialog.getVcodeTextView().setClickable(false);
					} else {
						showToast("请输入11位手机号");
					}

				}
			}, new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (dialog.getOldTelText().length() == 11) {

						if (dialog.getTelText().length() == 11) {

							if (dialog.getCodeText().length() == 6) {

								loginManager.checkVCode(dialog.getTelText(), dialog.getCodeText(), checkVCodeListener());

							} else {
								showToast("验证码为6位");
							}

						} else {
							showToast("新手机号为11位");
						}

					} else {
						showToast("原手机号为11位");
					}

				}
			});

			break;
		case R.id.personinfo_address:
			if (cityPicker == null) {
				cityPicker = new CityPickerDialog(this);
				cityPicker.setonAddressSelectedListener(this);
				CityCreator.getCityMaps(this, this);
			}
			cityPicker.show();
			break;

		default:
			break;
		}
	}

	@SuppressLint("InflateParams") @SuppressWarnings("deprecation")
	private void DisplayPhoto() {
		View view = PersonInfoActivity.this.getLayoutInflater().inflate(R.layout.dialog_takephotos, null);

		Button btn_takephoto1 = (Button) view.findViewById(R.id.btn_takephoto1);
		Button btn_takephoto2 = (Button) view.findViewById(R.id.btn_takephoto2);
		Button btn_takephoto_cancel = (Button) view.findViewById(R.id.btn_takephoto_cancel);
		btn_takephoto1.setOnClickListener(this);
		btn_takephoto2.setOnClickListener(this);
		btn_takephoto_cancel.setOnClickListener(this);

		pitcureDialog = new Dialog(PersonInfoActivity.this, R.style.transparentFrameWindowStyle);
		pitcureDialog.setContentView(view, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		Window window = pitcureDialog.getWindow();
		// 设置显示动画
		window.setWindowAnimations(R.style.main_menu_animstyle);
		WindowManager.LayoutParams wl = window.getAttributes();
		wl.x = 0;
		wl.y = PersonInfoActivity.this.getWindowManager().getDefaultDisplay().getHeight();

		wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
		wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

		// 设置显示位置
		pitcureDialog.onWindowAttributesChanged(wl);
		// 设置点击外围解散
		pitcureDialog.setCanceledOnTouchOutside(true);
		pitcureDialog.show();
	}
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		Uri uri;
		ImageUploader imageUploader = new ImageUploader(mActivity);

		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case 1:
				// Bitmap bitmap=BitmapFactory.decodeFile(photoFile.getPath());
				// personinfo_head.setImageBitmap(new ImageUploader(mActivity).compressBitmap(bitmap));
				Bitmap bitmap = BitmapFactory.decodeFile(photoFile.getPath());
				try {
					//Picasso.with(mActivity).load(imageUploader.bitmapTofile(imageUploader.compressBitmap(bitmap))).resize(720, 720).centerCrop().transform(new RoundedTransformationBuilder().oval(true).build()).into(personinfo_head);
					imageFile = imageUploader.bitmapTofile(imageUploader.compressBitmap(bitmap));
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				break;
			case 2:
				uri = data.getData();
				try {
					imageFile = imageLoader.bitmapTofile(imageLoader.compressBitmap(getBitmapFromUri(uri)));
				} catch (IOException e) {
					e.printStackTrace();
				}
				break;

			default:
				break;
			}
			
			Map<String, File> files = new HashMap<String, File>();
			files.put("img1", imageFile);
			loadingDialog.show();
			imageLoader.post(files);

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	private Bitmap getBitmapFromUri(Uri uri) {
		try {
			Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
			return bitmap;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 开启定时任务(主要是获取电话验证码)
	 */
	private final class DownTimer extends CountDownTimer {

		public DownTimer(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onTick(long millisUntilFinished) {
			// 倒计时开始
			long m = millisUntilFinished / 1000;
			String ss = String.valueOf(m % 3600 % 60);
			ss = twoLength(ss);
			if(dialog.isShowing())
				dialog.getVcodeTextView().setText(ss + " 秒");
			else {
				System.out.println("cancel");
				timer.cancel();
			}
		}

		/**
		 * 如果小于位，加0
		 * 
		 * @param str
		 * @return
		 */
		private String twoLength(String str) {
			if (str.length() == 1) {
				return str = "0" + str;
			}
			return str;
		}

		@Override
		public void onFinish() {
			dialog.getVcodeTextView().setClickable(true);
			dialog.getVcodeTextView().setText("重发");
		}
	}

	@Override
	public void onCityLoaded(final List<TCity> cities) {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				cityPicker.setData(cities);
				cityPicker.onLoadingCompleted();
			}
		});
	}

	@Override
	public void onAddressSelected(int areaId, String address) {
		dispatcher.address = address;
		loadingDialog.show();
		manager.alterAddress(LoginManager.getInstance(mActivity).getId(), areaId, alterAddressListener());
	}
	
	private NListener<BaseData> alterNameListener() {
		return new NListener<BaseData>() {
			@Override
			public void onResponse(BaseData data) {
				loadingDialog.dismiss();
				if (data.status == Constant.STATUS_OK) {
					ps_name.setText(dispatcher.name);
					LoginManager.getInstance(mActivity).saveUserInfo(dispatcher);
				} else {
					ToastMgr.show(data.msg);
				}
			}

			@Override
			public void onErrResponse(VolleyError error) {
				loadingDialog.dismiss();
			}

			@Override
			public void onAllPageLoaded(int nowPage, int totalPage) {
			}
		};
	}
	
	private NListener<BaseData> alterPhoneListener() {
		return new NListener<BaseData>() {
			@Override
			public void onResponse(BaseData data) {
				loadingDialog.dismiss();
				if (data.status == Constant.STATUS_OK) {
					ps_tel.setText(dispatcher.phone);
					LoginManager.getInstance(mActivity).saveUserInfo(dispatcher);
				} else {
					ToastMgr.show(data.msg);
				}
			}

			@Override
			public void onErrResponse(VolleyError error) {
				loadingDialog.dismiss();
			}

			@Override
			public void onAllPageLoaded(int nowPage, int totalPage) {
			}
		};
	}
	
	private NListener<BaseData> alterAddressListener() {
		return new NListener<BaseData>() {
			@Override
			public void onResponse(BaseData data) {
				loadingDialog.dismiss();
				if (data.status == Constant.STATUS_OK) {
					ps_address.setText(dispatcher.address);
					LoginManager.getInstance(mActivity).saveUserInfo(dispatcher);
				} else {
					ToastMgr.show(data.msg);
				}
			}

			@Override
			public void onErrResponse(VolleyError error) {
				loadingDialog.dismiss();
			}

			@Override
			public void onAllPageLoaded(int nowPage, int totalPage) {
			}
		};
	}
	
	private NListener<BaseData> getVCodeListener() {
		return new NListener<BaseData>() {
			@Override public void onResponse(BaseData data) {
				loadingDialog.dismiss();
				if (data.status == Constant.STATUS_OK) {
					//ToastMgr.show("验证码: " + data.data.vCode);
					dialog.getVcodeTextView().setText("59" + " 秒");
					dialog.getVcodeTextView().setClickable(false);
					timer.start();
				} else {
					ToastMgr.show(data.msg);
					dialog.getVcodeTextView().setClickable(true);
				}
			}

			@Override public void onErrResponse(VolleyError error) {
				loadingDialog.dismiss();
				dialog.getVcodeTextView().setClickable(true);
			}
			@Override public void onAllPageLoaded(int nowPage, int totalPage) {}
		};
	}
	
	private NListener<BaseData> checkVCodeListener() {
		return new NListener<BaseData>() {
			@Override public void onResponse(BaseData data) {
				loadingDialog.dismiss();
				if (data.status == Constant.STATUS_OK) {
					dialog.dismiss();
					dispatcher.phone = dialog.getTelText();
					loadingDialog.show();
					manager.alterPhone(LoginManager.getInstance(mActivity).getId(), dialog.getOldTelText(), dialog.getTelText(), alterPhoneListener());
				} else {
					ToastMgr.show(data.msg);
				}
			}

			@Override public void onErrResponse(VolleyError error) {
				loadingDialog.dismiss();
			}
			@Override public void onAllPageLoaded(int nowPage, int totalPage) {}
		};
	}
	
	private String icon;

	@Override
	public void onResultOk(int key, int resultCode, String data) {
		BaseData baseData = ImageUploader.parseResult(data);
		if(baseData.status == Constant.STATUS_OK) {
			icon = baseData.data.img1;
			manager.alterIcon(LoginManager.getInstance(mActivity).getId(), icon, uploadListener());
		} else {
			ToastMgr.show(baseData.msg);
		}
		
	}

	@Override
	public void onResultErr(int key, int resultCode, String data) {
		loadingDialog.dismiss();
		ToastMgr.show("网络异常");
	}
	
	private NListener<BaseData> uploadListener() {
		return new NListener<BaseData>() {
			@Override public void onResponse(BaseData data) {
				loadingDialog.dismiss();
				if (data.status == Constant.STATUS_OK) {
					dispatcher.icon = icon;
					LoginManager.getInstance(mActivity).saveUserInfo(dispatcher);
					Picasso.with(mActivity).load(dispatcher.icon).resize(480, 480).centerCrop().transform(new RoundedTransformationBuilder().oval(true).build()).into(personinfo_head);
				} else {
					ToastMgr.show(data.msg);
				}
			}

			@Override public void onErrResponse(VolleyError error) {
				loadingDialog.dismiss();
			}
			@Override public void onAllPageLoaded(int nowPage, int totalPage) {}
		};
	}

}
